<?php
// 单线程异步 IO

require 'HandleEvent.php';

$socket = stream_socket_server('tcp://0.0.0.0:9001', $errno, $errstr);

if (!$socket) {
    echo $errstr . PHP_EOL;
}

$eventBase = new EventBase();

$whats = Event::PERSIST | Event::READ | Event::WRITE;

$data = [];

$event = new \Event(
    $eventBase,
    $socket,
    $whats,
    function ($socket, $whats) use ($eventBase, &$data) {
        $conn = stream_socket_accept($socket);

        echo '开始了' . PHP_EOL;

        // 因为作用域的问题，嵌套相同的定义 可能会覆盖
        (new HandleEvent($eventBase, $conn, $whats))->handle($data);

        echo '结束了' . PHP_EOL;
    });

$event->add();

$data[(int) $socket][$whats] = $event;

$eventBase->loop();